package com.dragon.aipictures.manager.sharding.test;

import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

public class DynamicPictureTableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargets,
                                       ComplexKeysShardingValue<Long> shardingValue) {
        Map<String, Collection<Long>> columns = shardingValue.getColumnNameAndShardingValuesMap();
        Long spaceId = columns.get("spaceId").iterator().next();

        // 动态表名生成
        if (spaceId!=0) {
            String tableName = "picture_" + spaceId;
            //建表的操作，交给业务，业务说什么时候建表就建表，业务在创建空间的时候就会建表
//            createTableIfNotExist(tableName); // 自动建表
            return Collections.singleton(tableName);
        }

        // 静态分表规则（spaceType=0）
        Long pictureId = columns.get("pictureId").iterator().next();
        //这里可以后续改为hashmod
        int tableSuffix = (int)(pictureId % 10);
        return Collections.singleton("picture_0_" + tableSuffix);
    }


    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}